import {
    CustCareUserInfo,
    MessageListParam,
    SendMessage
} from '@/api/custcare/talk/BackUserModel'
import { getMessageListApi, getUploadApi } from '@/api/custcare/talk/back_user'
import { setMsgReadApi } from '@/api/custcare/visitor/visitor'
import { SetMsgReadParam } from '@/api/custcare/visitor/VisitorModel'
import useInstance from '@/hooks/useInstance'
import { StatusCode } from '@/http/request'
import { custCareUserStore } from '@/store/custcare'
import { IMessage } from '@/store/type'
import { MESSAGE_CMD, MESSAGE_TYPE } from '@/types/CustcareEnum'
import { getCustcareUserInfo } from '@/utils/custcareAuth'
import {
    formatDateHms,
    getNowTime,
    getNowTimeText
} from '@/utils/custcareFilters'
import { formatDate } from '@/utils/filters'
import { nextTick, onMounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'

export default function useChat(visitorInfo: any, emit: any) {
    const custStore = custCareUserStore()
    const route = useRoute()

    const { global } = useInstance()

    const talkLayoutHeight = ref(0)
    const mainLayoutHeight = ref(0)
    const baseURL = <string>import.meta.env.VITE_CUSTCARE_IMG_SERVER
    const msg = ref('')
    const isShowEmo = ref(false)
    const imgFileInput = ref<InstanceType<typeof HTMLInputElement>>()
    const isShowImg = ref(false)
    const showImgSrc = ref('/src/assets/icons/image-line.svg')
    const custCareUserInfo = reactive<CustCareUserInfo>({
        channel_id: '',
        service_uuid: '',
        uuid: '',
        nickname: '',
        avatar: '',
        service_client_ip: '',
        service_province: '',
        service_city: '',
        service_online: 0
    })

    const messageList = reactive({
        list: Array<IMessage>()
    })

    const trailCustcareRef = ref<{
        show: (clientIp: string, channelId: string, uuid: string) => void
    }>()

    const emos = ref([
        'amazed-face',
        'amusing-face',
        'anguished-face',
        'astonished-face',
        'backhand-index-pointing-down-1',
        'backhand-index-pointing-up-1',
        'beaming-face-with-smiling-eyes',
        'clapping-hands-1',
        'confounded-face',
        'crazy-face',
        'crying-face',
        'determined-face',
        'downcast-face-with-sweat',
        'drooling-face-1',
        'drooling-face-2',
        'face-blowing-a-kiss',
        'face-savoring-food',
        'face-screaming-in-fear',
        'face-vomiting',
        'face-with-head-bandage',
        'face-with-medical-mask',
        'face-with-monocle',
        'face-with-steam-from-nose',
        'face-with-symbols-on-mouth',
        'face-with-tears-of-joy',
        'face-with-tongue',
        'fearful-face',
        'flexed-biceps-1',
        'folded-hands-1',
        'frowning-face',
        'grimacing-face',
        'grinning-face',
        'grinning-face-with-smiling-eyes',
        'grinning-face-with-sweat',
        'grinning-squinting-face',
        'hushed-face-2',
        'index-pointing-up-1',
        'kissing-face-with-closed-eyes',
        'kissing-face-with-smiling-eyes',
        'loudly-crying-face',
        'money-mouth-face-1',
        'nauseated-face-2',
        'nerd-face',
        'ok-hand-1',
        'oncoming-fist-1',
        'persevering-face',
        'pouting-face',
        'raised-fist-1',
        'raised-hand-1',
        'shushing-face',
        'sleeping-face',
        'sleepy-face',
        'smiling-face-with-heart-eyes',
        'smiling-face-with-smiling-eyes',
        'smiling-face-with-sunglasses',
        'sneezing-face',
        'squinting-face-with-tongue',
        'star-struck-1',
        'star-struck-2',
        'thumbs-down-1',
        'thumbs-up-1',
        'victory-hand-1',
        'waving-hand-1'
    ])

    const handleSend = () => {
        const content = msg.value
        if (!content) {
            global.$message({ message: '请输入内容！', type: 'error' })
            return
        }
        sendMsg(MESSAGE_TYPE.TYPE_TEXT, content)

        msg.value = ''
    }

    const sendMsg = (type: number, content: string) => {
        console.log('发送消息', content)
        // custCareUserInfo.data
        const msg = reactive<SendMessage>({
            cmd: MESSAGE_CMD.CMD_MSG,
            channel_id: custCareUserInfo.channel_id,
            to_user_uuid: custCareUserInfo.service_uuid,
            type: type,
            content: content
        })
        custStore.getSocket.sendMessage(msg)
        const iMessage = reactive<IMessage>({
            msg_type: 'right', // left / right
            uuid: custCareUserInfo.uuid,
            nickname: custCareUserInfo.nickname,
            avatar: custCareUserInfo.avatar,
            client_ip: '',
            type: type,
            content: content,
            send_time: getNowTime(),
            send_time_text: getNowTimeText()
        })
        messageList.list.push(iMessage)
        setScrollTop()
    }

    const showEmo = () => {
        isShowEmo.value = !isShowEmo.value
    }

    const handleEmo = (emo: string) => {
        isShowEmo.value = false
        msg.value = msg.value + ':' + emo + ':'
    }

    const emotion = (res: string) => {
        let word = res.replace(/\:/gi, '')
        return `<img class="emotion" width="32px" height="32px" src="/src/assets/emo/streamlinehq-${word}-smiley-people-102.png">`
    }

    const handleImgFileChange = async (e: Event) => {
        const target = e.target as HTMLInputElement
        // console.log(target.files)
        if (target.files) {
            const files = Array.from(target.files)
            console.log('files=', files)
            if (files.length > 0) {
                // 取得文件
                const uploadedFile = files[0]
                console.log('uploadedFile=', uploadedFile)
                if (
                    uploadedFile.type == 'image/jpeg' ||
                    uploadedFile.type == 'image/png' ||
                    uploadedFile.type == 'image/gif'
                ) {
                    if (uploadedFile.size / 1024 / 1024 > 4) {
                        global.$message({
                            message: '图片大小不能超过4MB！',
                            type: 'error'
                        })
                        return false
                    }

                    const formData = new FormData()
                    formData.append('file', uploadedFile)

                    const res = await getUploadApi(formData)
                    console.log('上传结果', res)
                    if (res.code == StatusCode.Success) {
                        // 发送图片地址
                        sendMsg(MESSAGE_TYPE.TYPE_IMG, baseURL + res.data.path)
                    } else {
                        global.$message({
                            message: res.msg,
                            type: 'error'
                        })
                    }

                    return true
                } else {
                    global.$message({
                        message: '必须是JPG、PNG格式的图片！',
                        type: 'error'
                    })
                    return false
                }
            }
        }
    }

    const clickUploadImg = () => {
        imgFileInput.value?.click()
    }

    const handleShowImg = (imgSrc: string) => {
        showImgSrc.value = imgSrc
        isShowImg.value = true
    }

    const getHandleCustcareInfo = () => {
        const custcareInfo = getCustcareUserInfo()
        custCareUserInfo.channel_id = visitorInfo.channel_id
        custCareUserInfo.service_uuid = visitorInfo.uuid
        custCareUserInfo.uuid = custcareInfo.uuid
        custCareUserInfo.nickname = custcareInfo.nickname
        custCareUserInfo.avatar = custcareInfo.avatar
        custCareUserInfo.service_client_ip = visitorInfo.client_ip
        custCareUserInfo.service_province = visitorInfo.province
        custCareUserInfo.service_city = visitorInfo.city
        custCareUserInfo.service_online = visitorInfo.online
    }

    const getHandleMessages = async () => {
        const channelId = visitorInfo.channel_id
        const visitorId = visitorInfo.id
        const param = reactive<MessageListParam>({
            channel_id: channelId
        })
        let res = await getMessageListApi(param)
        if (res && res.code == StatusCode.Success) {
            // console.log('消息列表：', res.data.list)
            messageList.list = []
            if (res.data.list) {
                res.data.list.forEach((item: any) => {
                    let msg_type = 'right'
                    if (item.visitor_id == visitorId) {
                        msg_type = 'left'
                    }
                    const iMessage = reactive<IMessage>({
                        msg_type: msg_type, // left / right
                        uuid: custCareUserInfo.uuid,
                        nickname: custCareUserInfo.nickname,
                        avatar: custCareUserInfo.avatar,
                        client_ip: custCareUserInfo.service_client_ip,
                        type: item.type,
                        content: item.content,
                        send_time: item.created_at,
                        send_time_text: formatDate(item.created_at)
                    })
                    messageList.list.push(iMessage)
                })
                // console.log(messageList.list)
                setScrollTop()
            }
        }
    }

    // const theScrollTop = computed(() => {
    //     const count = messageList.list.length
    //     const target = document.querySelector('#messageList')
    //     if (target) {
    //         // console.log('scrollHeight=', target.scrollHeight)
    //         // target.scrollTo(0, target.scrollHeight)
    //         return target.scrollHeight
    //     } else {
    //         console.log('scrollHeight=', 0)
    //         return 0
    //     }
    //     return count
    // })

    // 设置成已读
    const setMsgRead = async () => {
        const param = reactive<SetMsgReadParam>({
            channel_id: visitorInfo.channel_id
        })
        let res = await setMsgReadApi(param)
        if (res && res.code == StatusCode.Success) {
            console.log(res.msg)
        } else {
            console.log(res)
        }
    }

    watch(custStore.getRealTimeMsg, (newRealTimeMsg, o) => {
        if (route.path == '/custcare/talk') {
            if (custCareUserInfo.service_uuid == newRealTimeMsg.user_uuid) {
                let msg_type = 'left'
                const iMessage = reactive<IMessage>({
                    msg_type: msg_type, // left / right
                    uuid: newRealTimeMsg.user_uuid,
                    nickname: '',
                    avatar: '',
                    client_ip: custCareUserInfo.service_client_ip,
                    type: newRealTimeMsg.type,
                    content: newRealTimeMsg.content,
                    send_time: newRealTimeMsg.send_time,
                    send_time_text: formatDateHms(newRealTimeMsg.send_time)
                })
                messageList.list.push(iMessage)
                setMsgRead()
                setScrollTop()

                if (newRealTimeMsg.type == MESSAGE_TYPE.TYPE_NOTIFY_OFFLINE) {
                    custCareUserInfo.service_online = 0
                } else if (
                    newRealTimeMsg.type == MESSAGE_TYPE.TYPE_NOTIFY_ONLINE
                ) {
                    custCareUserInfo.service_online = 1
                }
            } else {
                const iMessage = reactive<IMessage>({
                    msg_type: 'right', // left / right
                    uuid: custCareUserInfo.uuid,
                    nickname: custCareUserInfo.nickname,
                    avatar: custCareUserInfo.avatar,
                    client_ip: '',
                    type: newRealTimeMsg.type,
                    content: newRealTimeMsg.content,
                    send_time: newRealTimeMsg.send_time,
                    send_time_text: formatDateHms(newRealTimeMsg.send_time)
                })
                messageList.list.push(iMessage)
                setScrollTop()
            }
        }
    })

    const setScrollTop = () => {
        setTimeout(() => {
            const target = document.querySelector('#messageList')
            if (target) {
                target.scrollTo(0, target.scrollHeight)
            }
        }, 100)
    }

    const trailCustcare = (
        clientIp: string,
        channelId: string,
        uuid: string
    ) => {
        trailCustcareRef.value?.show(clientIp, channelId, uuid)
    }

    const onTrailChange = () => {
        emit('on-trail', '刷新对话列表2')
    }

    onMounted(() => {
        nextTick(() => {
            talkLayoutHeight.value = window.innerHeight - 150
            mainLayoutHeight.value = talkLayoutHeight.value - 250
            getHandleCustcareInfo()
            getHandleMessages()
            setMsgRead()
        })
    })

    return {
        talkLayoutHeight,
        mainLayoutHeight,
        msg,
        isShowEmo,
        imgFileInput,
        emos,
        messageList,
        handleSend,
        showEmo,
        handleEmo,
        emotion,
        handleImgFileChange,
        clickUploadImg,
        isShowImg,
        showImgSrc,
        handleShowImg,
        custCareUserInfo,
        trailCustcareRef,
        trailCustcare,
        onTrailChange
    }
}
